package org.wx.herostory.services.util.mq;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * @description: mq 生产者
 * @author: wangxun
 * @createDate: 2021/3/8
 * @version: 1.0
 */
@Slf4j
public class MqProducer {
    static private DefaultMQProducer _producer = null;
    private MqProducer(){}

    /**
     * 初始化
     */
    static public void init(){
        try {
            _producer = new DefaultMQProducer("herostory");
            _producer.setNamesrvAddr("test.wx.cn:9876");
            _producer.start();
            // 重试次数
            _producer.setRetryTimesWhenSendAsyncFailed(3);
            log.info("消息队列【生产者】初始化成功");
        } catch (MQClientException e) {
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 发送消息
     * @param topic 主题
     * @param msg 消息内容
     */
    static public void sendMsg(String topic,Object msg){
        if(null == topic || null == msg){
            return;
        }

        final Message message = new Message();
        message.setTopic(topic);
        message.setBody(JSONObject.toJSONBytes(msg));

        try {
            _producer.send(message);
            log.info("mq send is success");
        } catch (Exception e) {
            log.error("mq send is fail:{}",e.getMessage(),e);

        }
    }
}
